import { defineStore } from 'pinia'
import { isEmpty } from '@/utils'

export const useChatStore = defineStore('chat', () => {
  const ws = ref(null)
  const connecting = ref(false)
  const isConnect = ref(false)

  const currentUserName = ref('')
  const userList = ref([])
  const commentList = ref([])

  const hasNewComment = ref(false)
  const hasNewMyComment = ref(false)

  // 开始连接
  const openConnect = username => {
    showLoadingToast({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    })
    connecting.value = true
    ws.value = new WebSocket(import.meta.env.VITE_API + '?from=' + username)
    // 接收服务器发送的信息
    ws.value.onmessage = evt => {
      const message = JSON.parse(evt.data)

      if (message.code !== 0) {
        return
      }

      if (message.type === 'connect-fail') {
        showFailToast({ type: 'fail', message: '用户名被抢了！' })
        showNotify({ type: 'danger', message: '用户名被抢了！' })
        currentUserName.value = ''
        isConnect.value = false
        return
      }

      if (message.type === 'connect-success') {
        connecting.value = false
        closeToast()
        currentUserName.value = message.data
        showSuccessToast('聊天室连接成功！')
        isConnect.value = true
        return
      }

      if (message.type === 'userlist') {
        userList.value = message.data
        return
      }

      if (message.type === 'comment-add') {
        commentList.value.push(message.data)

        // 有他人发出的新消息
        if (message.data.username !== currentUserName.value) {
          hasNewComment.value = true
        } else {
          hasNewMyComment.value = true
        }

        return
      }
    }

    ws.value.onerror = evt => {
      console.log('error: ', evt)
      isConnect.value = false
    }

    ws.value.onclose = evt => {
      console.log('close: ', evt, evt.code)
      connecting.value = false
      closeToast()
      if (evt.code === 1006) {
        showFailToast({ type: 'fail', message: '失去聊天室连接' })
        showNotify({ type: 'warning', message: '失去聊天室连接' })
      }
      isConnect.value = false
      currentUserName.value = ''
      commentList.value = []
      userList.value = []
    }
  }

  // 发送评论
  const sendComment = comment => {
    if (!ws.value) return
    if (!isConnect.value) return
    if (isEmpty(comment)) {
      showToast('请输入评论')
      return
    }

    const param = {
      module: 'comment',
      type: 'comment-add',
      data: {
        username: currentUserName.value,
        time: dayjs().valueOf(),
        comment,
      },
    }
    const paramsString = JSON.stringify(param)
    ws.value.send(paramsString)
  }

  return {
    ws,
    connecting,
    isConnect,
    currentUserName,
    userList,
    commentList,
    hasNewComment,
    hasNewMyComment,
    openConnect,
    sendComment,
  }
})
